package com.chuangjiangx.member.basic.ddd.domain.model;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * 微信访问的ACCESS_TOKEN
 *
 * @author 马文韬
 * @version 1.0
 * @date: 2018/9/14
 */
@Data
public final class WxAccessToken {

    /**
     * 申请凭证的 app_id
     */
    private String appId;

    /**
     * 申请凭证的 app_secret
     */
    private String appSecret;

    /**
     * 凭证，ACCESS_TOKEN
     */
    private String accessToken;

    /**
     * 申请（创建）时间
     */
    private Date createTime;

    /**
     * 凭证有效时间，单位：秒
     */
    private Long expiresIn;

    public WxAccessToken(String appId, String appSecret, String accessToken, Long expiresIn) {
        this.appId = appId;
        this.appSecret = appSecret;
        this.accessToken = accessToken;
        this.expiresIn = expiresIn;

        this.createTime = new Date();
    }

    /**
     * 凭证
     */
    public String value() {
        return getAccessToken();
    }

    /**
     * 凭证过期时间
     */
    public Date expiresTime() {
        LocalDateTime time = LocalDateTime.ofInstant(getCreateTime().toInstant(), ZoneId.systemDefault());
        LocalDateTime newTime = time.plusSeconds(getExpiresIn());
        Instant instant = newTime.atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

    /**
     * ACCESS_TOKEN 是否有效
     */
    public boolean available() {
        Date nowDate = new Date();
        return !StringUtils.isEmpty(value())
                 &&
                expiresTime().getTime() > nowDate.getTime();
    }
}
